package com.logbug.reflect;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

public class TestProxy {
    interface Person {
        public void work();
    }

    static class Teacher implements Person {

        @Override
        public void work() {
            System.out.println("教书育人");
        }

        @Override
        public String toString() {
            return "教师";
        }
    }

    static class WorkHandler implements InvocationHandler {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//            System.out.println(proxy);
            method.invoke(proxy, args);
            return null;
        }
    }

    public static void main(String[] args) {

        proxyMap();
        proxyHashMap();


    }

    public static void proxyMap() {
//        Proxy.java 第538行调试，执行下面代码可以导出该代理类文件
//        new FileOutputStream("/Users/chenlin/Downloads/tt/proxy.class").write(proxyClassFile)

Map map = (Map) Proxy.newProxyInstance(TestProxy.class.getClassLoader(), new Class[]{Map.class}, (proxy, method, args1) -> {
    if (method.getName() == "get") {
        return "world";
    } else {
        System.out.println("不支持该方法调用");
        return null;
    }
});

System.out.println("hello  " + map.get("hello"));
map.put("a", "b");
    }

    public static void proxyHashMap() {
        Map hashMap = new HashMap();
        Map map = (Map) Proxy.newProxyInstance(TestProxy.class.getClassLoader(), new Class[]{Map.class}, (proxy, method, args) -> {
            System.out.println("before method " + method.getName() + " invoke.");
            Object result = method.invoke(hashMap, args);
            System.out.println("after method " + method.getName() + " invoke.");
            return result;
        });
        System.out.println("存入  a=b");
        map.put("a", "b");
        System.out.println("取出 a = " + map.get("a"));
    }
}
